package com.redwinter.logkit.sdk.parser;

import com.redwinter.logkit.sdk.annotation.BizLogRecord;
import com.redwinter.logkit.sdk.context.LogSpELVarContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author goudadong
 * @description 使用Spring实现日志解析器
 * @datetime 2021-12-14 14:43
 * @email 2360564660@qq.com
 **/
public class SpringLogAnnotationParser implements LogParser {

    private static final Set<Class<? extends Annotation>> LOG_OPERATION_ANNOTATIONS = new LinkedHashSet<>(128);

    static {
        LOG_OPERATION_ANNOTATIONS.add(BizLogRecord.class);
    }

    @Override
    public Collection<LogOperation> parseLogRecordAnnotations(Method method) {
        return parseLogAnnotations(method);
    }

    private Collection<LogOperation> parseLogAnnotations(AnnotatedElement el) {
        Collection<? extends Annotation> annotations = AnnotatedElementUtils.findAllMergedAnnotations(el, LOG_OPERATION_ANNOTATIONS);
        if (annotations.isEmpty()) {
            return null;
        }
        final Collection<LogOperation> ops = new ArrayList<>(1);
        annotations.stream().filter(ann -> ann instanceof BizLogRecord).forEach(
                ann -> ops.add(parseLogRecord(el, (BizLogRecord) ann)));
        return ops;
    }

    private LogOperation parseLogRecord(AnnotatedElement el, BizLogRecord logRecord) {
        return new LogOperation(el.toString(), logRecord.bizType(), logRecord.data(), logRecord.condition());
    }
}
